package com.dexilaonian.fragment;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.dexilaonian.MainActivity;
import com.dexilaonian.R;
import com.dexilaonian.activity.HomeAgingActivity;
import com.dexilaonian.activity.HomeNursingActivity;
import com.dexilaonian.activity.HouseKeepActivity;
import com.dexilaonian.activity.LocalUtils;
import com.dexilaonian.activity.LoginActivity;
import com.dexilaonian.activity.Piety_card;
import com.dexilaonian.activity.RecoveryActivity;
import com.dexilaonian.activity.SelectCityActivity;
import com.dexilaonian.activity.ServiceActivity;
import com.dexilaonian.adpter.GridAdapter;
import com.dexilaonian.bean.HomeBean;
import com.dexilaonian.ui.BaseFragment;
import com.dexilaonian.utils.Constant;
import com.dexilaonian.utils.JsonUtil;
import com.dexilaonian.utils.Logutil;
import com.dexilaonian.utils.Okhttp;
import com.dexilaonian.utils.PreferencesUtil;
import com.dexilaonian.view.MyGridView;
import com.dexilaonian.view.SlideShowView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class DoorServiceFragment extends BaseFragment {
    @Bind(R.id.weizhi)
    ImageView weizhi;
    @Bind(R.id.home_address)
    TextView homeAddress;
    @Bind(R.id.slideshow)
    SlideShowView slideshow;
    @Bind(R.id.ll_home_recovery)
    LinearLayout llHomeRecovery;
    @Bind(R.id._ll_housekeeping)
    LinearLayout LlHousekeeping;
    @Bind(R.id.ll_home_nursing)
    LinearLayout llHomeNursing;
    @Bind(R.id.ll_home_aging)
    LinearLayout llHomeAging;
    @Bind(R.id.ll_piety_card)
    LinearLayout llPietyCard;
    @Bind(R.id.rl_call)
    ImageView rlCall;
    @Bind(R.id.home_gridview)
    MyGridView homeGridview;
    @Bind(R.id.scrollView)
    ScrollView scrollView;
    private String auto_url = Constant.base_url + "/banner/getBanners";
    private String home_url = Constant.base_url + "/partner/list";
    private List<View> home_list = new ArrayList<>();
    private List<HomeBean> list_grid = new ArrayList();
    private String MyCity = "深圳";
    private Intent intent;
    private String selectcity = "";
    private FragmentActivity mContext;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (mContext == null) {
            mContext = getActivity();
        }
        MainActivity activity = (MainActivity)mContext;
        selectcity = activity.getCity();
    }
    @Override
    protected void initData(Bundle savedInstanceState) {
    }

    @Override
    protected void initView(View layoutView) {

    }
    @Override
    public int getLayoutID() {
        return R.layout.fragment_doorservice;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        new Thread(new Runnable() {
            @Override
            public void run() {
                initAuto();
            }
        }).start();
        initHome();
        if (TextUtils.isEmpty(selectcity)) {
        //init();
        } else {
            homeAddress.setText(selectcity);
        }
        scrollView.smoothScrollTo(0, 20); //回到顶部
    }
    //定位
    private void getLocation() {
        LocalUtils localUtils = new LocalUtils(mContext, new LocalUtils.OnLocationListener() {
            @Override
            public void locationListener(final String city) {
                mContext.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (city != null) {
                            PreferencesUtil.putString(mContext, Constant.CITY, city);
                            homeAddress.setText(city);
                            MyCity = city;
                        }
                    }
                });
            }
        });
        localUtils.startLocation();
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
    private void init() {
        //请求定位允许
        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(mContext, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 12);
            getLocation();
        } else {
            getLocation();
        }
    }
    //轮播图
    private void initAuto() {
        OkHttpUtils.post().url(auto_url).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
            }

            @Override
            public void onResponse(String response, int id) {
                ArrayList<String> bannerPics = new ArrayList<String>();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int status = Integer.parseInt(jsonObject.optString("status"));
                    if (status == 34 || status == 16) {
                        startActivity(new Intent(mContext, LoginActivity.class));
                        return;
                    }
                    if (!jsonObject.toString().equals("")) {
                        String data1 = jsonObject.optString("data");
                        if (!TextUtils.isEmpty(data1)) {
                            JSONArray json = new JSONArray(data1);
                            for (int i = 0; i < json.length(); i++) {
                                String imagePath = json.getString(i);
                                JSONObject jsono = new JSONObject(imagePath);
                                String banner = jsono.optString("banner");
                                bannerPics.add(Constant.base_pic_url + banner);
                            }
                            slideshow.setData(bannerPics,mContext);
                            slideshow.initShow();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void initHome() {
        Map<String, String> map = new HashMap<>();
        Okhttp.postString(false, home_url, map, new Okhttp.CallBac() {
            @Override
            public void onError(Call call, Exception e, String state, int id) {
                showToast(e.getMessage());
            }
            @Override
            public void onResponse(String response, int id) {
                Logutil.e(response);
                try {
                    JSONObject object = new JSONObject(response);
                    int status = Integer.parseInt(object.optString("status"));
                    if (status == 34 || status == 16) {
                        startActivity(new Intent(mContext, LoginActivity.class));
                        return;
                    }
                    String data2 = object.optString("data");
                    if (!TextUtils.isEmpty(data2)) {
                        ArrayList<HomeBean> homeBeen = JsonUtil.json2beans(data2, HomeBean.class);
                        list_grid.clear();
                        list_grid.addAll(homeBeen);
                        GridAdapter gridAdapter = new GridAdapter(mContext, list_grid);
                        homeGridview.setAdapter(gridAdapter);
                        gridAdapter.notifyDataSetChanged();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNoNetwork(String state) {
                showToast(state);
            }
        });
    }
    @OnClick({R.id.ll_piety_card, R.id.home_address, R.id.ll_home_recovery, R.id._ll_housekeeping, R.id.ll_home_nursing, R.id.ll_home_aging, R.id.rl_call})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.home_address:
            case R.id.weizhi:
                startActivity(new Intent(mContext, SelectCityActivity.class));
                break;
            case R.id.ll_home_recovery:
                intent = new Intent(mContext, RecoveryActivity.class);
                intent.putExtra("City",MyCity);
                startActivity(intent);
                break;
            case R.id._ll_housekeeping:
                intent = new Intent(mContext, HouseKeepActivity.class);
                intent.putExtra("City",MyCity);
                startActivity(intent);
                break;
            case R.id.ll_home_nursing:
                intent = new Intent(mContext, HomeNursingActivity.class);
                intent.putExtra("City",MyCity);
                startActivity(intent);
                break;
            case R.id.ll_home_aging:
                startActivity(new Intent(mContext, HomeAgingActivity.class));
                break;
            case R.id.rl_call:
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                builder.setTitle("确定拨打0755-26915967？");
                builder.setIcon(R.drawable.dianhua);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Intent.ACTION_DIAL);
                        Uri data = Uri.parse("tel:" + "075526915967");
                        intent.setData(data);
                        startActivity(intent);
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                builder.show();
                break;
            case R.id.ll_piety_card:
                initService();
                break;
        }
    }
    private void initService() {
        showProgressBar(true);
        Map<String, String> map = new HashMap<>();
        String vip_url =Constant.base_url + "/vipCard/list.do";;
        Okhttp.postString(true, vip_url, map, new Okhttp.CallBac() {
            @Override
            public void onError(Call call, Exception e, String state, int id) {
                showProgressBar(false);
            }

            @Override
            public void onResponse(String response, int id) {
                showProgressBar(false);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int status = Integer.parseInt(jsonObject.optString("status"));
                    if (status == 35) {
                        intent = new Intent(mContext, ServiceActivity.class);
                        intent.putExtra("CONFIRM", "");
                        startActivity(intent);
                        return;
                    }
                    startActivity(new Intent(mContext, Piety_card.class));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onNoNetwork(String state) {
                showProgressBar(false);
            }
        });
    }

}
